package org.jeecg.modules.platform.member.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.ServiceNameConstants;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.platform.api.PlatformOrganizationMemberApi;
import org.jeecg.modules.platform.entity.CyPlatformOrganizationAndMember;
import org.jeecg.modules.platform.entity.CyPlatformOrganizationInfo;
import org.jeecg.modules.platform.member.service.ICyPlatformOrganizationAndMemberService;
import org.jeecg.modules.platform.organization.service.ICyPlatformOrganizationInfoService;
import org.jeecg.modules.user.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 组织和用户关系
 * @Author: jeecg-boot
 * @Date: 2024-10-28
 * @Version: V1.0
 */
@Api(tags = "组织用户")
@RestController
@RequestMapping(ServiceNameConstants.PATH_MEMBER)
@Slf4j
public class CyPlatformOrganizationAndMemberController extends JeecgController<CyPlatformOrganizationAndMember, ICyPlatformOrganizationAndMemberService> implements PlatformOrganizationMemberApi {
    @Autowired
    private ICyPlatformOrganizationAndMemberService cyPlatformOrganizationAndMemberService;
    @Autowired
    private ICyPlatformOrganizationInfoService orgService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private RedisUtil redisUtil;
    /**
     * 分页列表查询
     *
     * @param cyPlatformOrganizationAndMember
     * @param pageNo
     * @param pageSize
     * @param req
     *
     * @return
     */
    //@AutoLog(value = "组织和用户关系-分页列表查询")
    @ApiOperation(value = "组织和用户关系-分页列表查询", notes = "组织和用户关系-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<CyPlatformOrganizationAndMember>> queryPageList(CyPlatformOrganizationAndMember cyPlatformOrganizationAndMember,
                                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                        HttpServletRequest req) {
        QueryWrapper<CyPlatformOrganizationAndMember> queryWrapper = QueryGenerator.initQueryWrapper(cyPlatformOrganizationAndMember, req.getParameterMap());
        Page<CyPlatformOrganizationAndMember> page = new Page<CyPlatformOrganizationAndMember>(pageNo, pageSize);
        IPage<CyPlatformOrganizationAndMember> pageList = cyPlatformOrganizationAndMemberService.pageList(page, cyPlatformOrganizationAndMember);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param cyPlatformOrganizationAndMember
     *
     * @return
     */
    @AutoLog(value = "组织和用户关系-添加")
    @ApiOperation(value = "组织和用户关系-添加", notes = "组织和用户关系-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:cy_platform_organization_and_member:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody CyPlatformOrganizationAndMember cyPlatformOrganizationAndMember) {
        CyPlatformOrganizationAndMember member = this.service.getOne(new LambdaQueryWrapper<CyPlatformOrganizationAndMember>().eq(CyPlatformOrganizationAndMember::getUserId, cyPlatformOrganizationAndMember.getUserId()).eq(CyPlatformOrganizationAndMember::getOrganizationId, cyPlatformOrganizationAndMember.getOrganizationId()));
        if (member != null) {
            return Result.error("该用户已绑定该组织，请勿重复绑定！");
        }
        // 绑定个人和组织
        cyPlatformOrganizationAndMemberService.save(cyPlatformOrganizationAndMember);

        SysUser user = userService.getById(cyPlatformOrganizationAndMember.getUserId());
        CyPlatformOrganizationInfo organizationInfo = orgService.getById(cyPlatformOrganizationAndMember.getOrganizationId());

        // 未绑定组织的，绑定组织；
        if (StringUtils.isEmpty(user.getOrganizationId())) {
            user.setOrganizationId(cyPlatformOrganizationAndMember.getOrganizationId());
            user.setDepartId(organizationInfo.getDeptId());
            userService.updateById(user);
            redisUtil.del(CacheConstant.SYS_USERS_CACHE + "::" + user.getUsername());
        }
        return Result.OK("添加成功！");
    }

    /**
     * 通过id删除
     *
     * @param id
     *
     * @return
     */
    @AutoLog(value = "组织和用户关系-通过id删除")
    @ApiOperation(value = "组织和用户关系-通过id删除", notes = "组织和用户关系-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:cy_platform_organization_and_member:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        CyPlatformOrganizationAndMember member = this.service.getById(id);
        SysUser user = userService.getById(member.getUserId());
        if (user.getOrganizationId().equals(member.getOrganizationId())) {
            user.setOrganizationId("");
            user.setDepartId("");
            // 查询还在绑定中的组织
            CyPlatformOrganizationAndMember lastMember = this.service.getOne(new LambdaQueryWrapper<CyPlatformOrganizationAndMember>()
                    .eq(CyPlatformOrganizationAndMember::getUserId, member.getUserId())
                    .orderByDesc(CyPlatformOrganizationAndMember::getCreateTime)
                    .last("limit 1"));
            if (lastMember != null) {
                CyPlatformOrganizationInfo organizationInfo = orgService.getById(lastMember.getOrganizationId());
                user.setOrganizationId(lastMember.getOrganizationId());
                user.setDepartId(organizationInfo.getId());
            }
            userService.updateById(user);
            redisUtil.del(CacheConstant.SYS_USERS_CACHE + "::" + user.getUsername());
        }
        cyPlatformOrganizationAndMemberService.removeById(id);
        return Result.OK("取消关联成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     *
     * @return
     */
    //@AutoLog(value = "组织和用户关系-通过id查询")
    @ApiOperation(value = "组织和用户关系-通过id查询", notes = "组织和用户关系-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<CyPlatformOrganizationAndMember> queryById(@RequestParam(name = "id", required = true) String id) {
        CyPlatformOrganizationAndMember cyPlatformOrganizationAndMember = cyPlatformOrganizationAndMemberService.getById(id);
        if (cyPlatformOrganizationAndMember == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(cyPlatformOrganizationAndMember);
    }

    @GetMapping(value = "/switch")
    @ApiOperation(value = "管理员开关", notes = "管理员开关")
    public Result<String> switchOrg(@RequestParam String id, @RequestParam Boolean bind) {
        this.service.update(
                new LambdaUpdateWrapper<CyPlatformOrganizationAndMember>()
                        .eq(CyPlatformOrganizationAndMember::getId, id)
                        .set(CyPlatformOrganizationAndMember::getDefaultBind, bind)
        );
        return Result.OK();
    }


    @Override
    public Result<List<CyPlatformOrganizationInfo>> listOrg(String userId) {

        // 未传入用户ID时，从当前用户获取
        if (StringUtils.isEmpty(userId)) {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            userId = loginUser.getId();
        }

        // 如果未登录，返回错误
        if (StringUtils.isEmpty(userId)) {
            return Result.error("未获取到用户信息");
        }

        List<CyPlatformOrganizationAndMember> orgMemberList = this.service.list(new LambdaQueryWrapper<CyPlatformOrganizationAndMember>()
                .eq(CyPlatformOrganizationAndMember::getUserId, userId));

        if (CollectionUtil.isEmpty(orgMemberList)) {
            return Result.ok();
        }

        List<CyPlatformOrganizationInfo> orgList = orgService.list(new LambdaQueryWrapper<CyPlatformOrganizationInfo>()
                .select(CyPlatformOrganizationInfo::getId, CyPlatformOrganizationInfo::getName)
                .in(CyPlatformOrganizationInfo::getId, orgMemberList.stream().map(CyPlatformOrganizationAndMember::getOrganizationId).collect(Collectors.toList())));

        return Result.ok(orgList);
    }

    @Override
    public Result<Boolean> checkAdmin(String userId, String orgId) {
        if (StringUtils.isEmpty(userId)) {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            userId = loginUser.getId();
            if (StringUtils.isEmpty(orgId)) {
                orgId = loginUser.getOrganizationId();
            }
        }

        CyPlatformOrganizationAndMember member = this.service.getOne(new LambdaQueryWrapper<CyPlatformOrganizationAndMember>()
                .eq(CyPlatformOrganizationAndMember::getUserId, userId)
                .eq(CyPlatformOrganizationAndMember::getOrganizationId, orgId));
        return Result.OK(member.getDefaultBind());
    }

}
